﻿using Microsoft.Exchange.WebServices.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using XF.Common;
using XF.Meeting.DAL;
using XF.Meeting.Entity.DTO;
using XF.Meeting.Entity.Enum;
using XF.Meeting.Entity.Query;

namespace EWS
{
    public class ExChangeHelper
    {
        private static readonly ExchangeVersion EwsVersion = (ExchangeVersion)Convert.ToInt32(ConfigHelper.GetConfg("EwsVersion"));
        private static readonly string EWSUrl = ConfigHelper.GetConfg(ConfigKeys.EWSUrl.ToString());
        private static readonly string EWSAccount = ConfigHelper.GetConfg("EWSAccount");
        private static readonly string EWSAccountPwd = ConfigHelper.GetConfg("EWSAccountPwd");
        public static ExchangeService service;
        public ExchangeService _config = null;
        private static ExchangeToDbService etsservice = new ExchangeToDbService("", "");
        static ExchangeToDbDal dal = new ExchangeToDbDal();
        public ExChangeHelper()
        {
            service = new ExchangeService(EwsVersion);
            service.Credentials = new WebCredentials(EWSAccount, EWSAccountPwd);
            service.Url = new Uri(EWSUrl);
        }
        public ExChangeHelper(O365Config config)
        {
            _config = new ExchangeService((ExchangeVersion)config.version);
            _config.Credentials = new WebCredentials(config.ewsAccount, config.ewsPwd);
            _config.Url = new Uri(config.ewsUrl);
        }
        public ExChangeHelper(int version, string account, string ewsPwd, string ewsUrl)
        {
            service = new ExchangeService((ExchangeVersion)version);
            service.Credentials = new WebCredentials(account, UCommonWork.Common.Commons.MD5DecodeString(ewsPwd));
            service.Url = new Uri(ewsUrl);
        }

        public static async Task<List<EmailEntity>> GetEmailListByRoom(string address)
        {
            var roomService = getExChangeHelper(address);
            // var roomService = ExChangeHelper.getExChangeHelper("zwg@3dmedcare.com");
            var list = new List<EmailEntity>();

            var aaa = GetMeeting(roomService, DateTime.Today, DateTime.Now.AddDays(180));
            var ccc = aaa.Where(i => i.AppointmentType == AppointmentType.Single).ToList();
            //   GetRecurringMeeting(roomService);
            await GetEmailEntityForRoom(roomService, list, ccc);
            return list;
        }

        private static async System.Threading.Tasks.Task<List<EmailEntity>> GetEmailEntityForRoom(ExchangeService roomService, List<EmailEntity> list, List<Appointment> aaa)
        {
            foreach (var roomMeet in aaa)
            {
                try
                {
                    await GetMeet(roomService, list, roomMeet);

                }
                catch (Exception e)
                {
                    continue;
                }


            }
            return list;
        }

        private static System.Threading.Tasks.Task GetMeet(ExchangeService roomService, List<EmailEntity> list, Appointment roomMeet)
        {
            try
            {


                Appointment item = Appointment.Bind(roomService, roomMeet.Id, new PropertySet(AppointmentSchema.Organizer));
                var UserService = ExChangeHelper.getExChangeHelper(item.Organizer.Address);
                var view = new CalendarView(roomMeet.Start, roomMeet.End);
                view.PropertySet = new PropertySet(AppointmentSchema.ICalUid);
                //var userMeet = UserService.FindAppointments(WellKnownFolderName.Calendar,view);
                CalendarFolder calendar = CalendarFolder.Bind(UserService, WellKnownFolderName.Calendar, new PropertySet());
                // Set the start and end time and number of appointments to retrieve.

                // Limit the properties returned to the appointment's subject, start time, and end time.
                FindItemsResults<Appointment> appointments = calendar.FindAppointments(view);
                var id = appointments.Where(i => i.ICalUid == roomMeet.ICalUid).FirstOrDefault();
                Appointment oApt = Appointment.Bind(UserService, id.Id, new PropertySet(ItemSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End, ItemSchema.Body, AppointmentSchema.RequiredAttendees, AppointmentSchema.Organizer, AppointmentSchema.Location, ItemSchema.Id, AppointmentSchema.ICalUid, AppointmentSchema.IsRecurring, AppointmentSchema.AppointmentType));
                var opp = getEmailEntity(oApt);
                //   dal.InsertTemp(opp, out string s);
                InsertOrUpdate(opp);
                list.Add(opp);
                return System.Threading.Tasks.Task.CompletedTask;
            }
            catch (Exception)
            {

                return System.Threading.Tasks.Task.CompletedTask;
            }
        }
        private static Task<bool> InsertOrUpdate(XF.Meeting.Entity.DTO.EmailEntity meet)
        {

            bool check = dal.CheckIsCreated(meet);
            if (check)
            {
                Task<bool> b = dal.InsertSingleTemp(meet, out string ss);
                return dal.Update(meet, out ss);

            }
            else
            {
                meet.SourceType = 2;
                Task<bool> b = dal.InsertSingleTemp(meet, out string ss);
                var (result, id) = dal.Insert(meet, out ss).Result;
                double time = (meet.Start - DateTime.Now).TotalMinutes;
                bool isTen = false;
                isTen = time > 10 ? false : true;
                if (result && meet.state == 1)
                {
                    //var wx = new WeChatHelper();
                    //wx.SendWxMssage(new CRoomPadQuery()
                    //{
                    //    CInfoId = id,
                    //    type = 1

                    //}, isTen);
                }
                return System.Threading.Tasks.Task.FromResult(result);
            }
        }
        public static List<EmailEntity> GetZhouqiEmailListByRoom(string address)
        {
            var roomService = ExChangeHelper.getExChangeHelper(address);
            //  var roomService = ExChangeHelper.getExChangeHelper("mwx@xfservice.com");
            var list = new List<EmailEntity>();
            List<Appointment> foundAppointments = new List<Appointment>();
            // Create a search filter based on the start search date.
            SearchFilter.SearchFilterCollection searchFilter = new SearchFilter.SearchFilterCollection();
            //每天同步s
            int EWSZhouQiDays = Convert.ToInt32(ConfigHelper.GetConfg("EWSZhouQiDays"));
            searchFilter.Add(new SearchFilter.IsGreaterThanOrEqualTo(AppointmentSchema.Start, DateTime.Today.AddDays(-EWSZhouQiDays)));
            //重新同步。
            //searchFilter.Add(new SearchFilter.IsGreaterThanOrEqualTo(AppointmentSchema.Start, DateTime.Now.AddDays(-1)));
            // Create an item view to specify which properties to return.
            ItemView ccview = new ItemView(1000);
            ccview.PropertySet = new PropertySet(BasePropertySet.IdOnly,
                                               AppointmentSchema.Subject,
                                               AppointmentSchema.Start,
                                               AppointmentSchema.AppointmentType,
                                               AppointmentSchema.IsRecurring);
            // Get the appointment items from the server with the properties we specified.
            FindItemsResults<Item> findResults = roomService.FindItems(WellKnownFolderName.Calendar, searchFilter, ccview);
            // Add each of the appointments of the type you want to the collection.

            //       CalendarFolder calendar = CalendarFolder.Bind(roomService, WellKnownFolderName.Calendar, new PropertySet());
            //   CalendarView cView = new CalendarView(DateTime.Now, DateTime.Now.AddDays(180), 1000);
            //cView.PropertySet = new PropertySet(BasePropertySet.FirstClassProperties);
            //       FindItemsResults<Appointment> appointments = calendar.FindAppointments(cView);
            foreach (Item item in findResults.Items)
            {
                Appointment appt = item as Appointment;
                if (appt.AppointmentType != AppointmentType.Single)
                {
                    foundAppointments.Add(appt);
                }
                else
                {
                    continue;
                }
            }
            var aa = foundAppointments;

            InsertZhouqiMeeting(roomService, aa);
            return list;
        }

        public static void InsertZhouqiMeeting(ExchangeService roomService, List<Appointment> aa)
        {
            var list = new List<Appointment>();
            try
            {


                for (int i = 0; i < aa.Count; i++)
                {
                    Appointment calendarItem = aa[i];
                    Appointment recurrMaster;
                    switch (calendarItem.AppointmentType)
                    {
                        // Calendar item is a recurring master so use Appointment.Bind
                        case AppointmentType.RecurringMaster:
                            recurrMaster = Appointment.Bind(service, aa[i].Id);
                            list.Add(recurrMaster);
                            break;
                        case AppointmentType.Occurrence:
                            recurrMaster = Appointment.BindToRecurringMaster(service, aa[i].Id);
                            list.Add(recurrMaster);
                            break;
                        // The calendar item is an exception to the series, so use BindToRecurringMaster.                
                        case AppointmentType.Exception:
                            recurrMaster = Appointment.BindToRecurringMaster(service, aa[i].Id);
                            list.Add(recurrMaster);
                            break;
                    }
                }
                list = list.Distinct().ToList();
                bool check = false;
                var email = new EmailEntity();
                foreach (var item in list)
                {
                    string userAddress = item.Organizer.Address;
                    var maill = GetEmailListByItemID(new ExchangeQuery(item.ICalUid, item.Organizer.Address, item.Start.AddDays(-1), item.End.AddDays(1))).Result;
                    email = getEmailEntity(maill, userAddress);
                    check = dal.CheckIsCreatedForZhouqi(email);
                    if (check)
                    {
                        etsservice.updateZhouqi(maill);
                    }
                    else
                    {
                        etsservice.insertZhouqi(maill);
                    }



                }
            }
            catch (Exception e)
            {

                throw;
            }


        }



        private static EmailEntity getEmailEntity(Appointment email, string userAddress = "")
        {

            EmailEntity meet = new EmailEntity();
            meet.Start = email.Start;
            meet.End = email.End;
            meet.Body = "";
            meet.Subject = email.Subject;
            meet.Organizer = email.Organizer == null ? userAddress : email.Organizer.Address;
            meet.Location = email.Location;
            meet.AttendeesList = email.RequiredAttendees.Select(i => new Attendeee(i.Address, i.Name)).ToList();
            meet.ID = email.ICalUid;
            meet.itemId = email.Id.UniqueId;
            //会议状态
            int state = 0;
            //会议时长
            var CRoomIDs = new StringBuilder();
            string[] CRoomNames = meet.Location.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            string CroomName = "";
            for (int i = 0; i < CRoomNames.Length; i++)
            {
                CroomName = CRoomNames[i];
                if (CroomName.Contains("天一阁"))
                {
                    CRoomIDs.Append(dal.GetRoomrIDByName("天一阁")).Append(",");
                }
                else
                {
                    if (CroomName.Contains("（"))
                    {
                        CRoomIDs.Append(dal.GetRoomrIDByName(CroomName.Split('（')[0])).Append(",");
                    }
                    else
                    {

                        if (CroomName.Contains(";"))
                        {
                            var croomNames = CroomName.Split(';');

                            foreach (var item in croomNames)
                            {
                                CRoomIDs.Append(dal.GetRoomrIDByName(item)).Append(",");
                            }

                        }
                        else
                        {
                            CRoomIDs.Append(dal.GetRoomrIDByName(CroomName)).Append(",");
                        }

                    }

                }

            }
            meet.CRoomIDs = CRoomIDs.ToString();
            //内部参会人ID  以,隔开
            var ParticipantIDs = new StringBuilder();
            try
            {
                var min = meet.End - meet.Start;
                meet.timelength = Convert.ToInt32(min.TotalMinutes.ToString());
            }
            catch (Exception)
            {
                meet.timelength = 0;
            }

            meet.CycleMeetGuid = Guid.NewGuid().ToString();
            //已结束
            if (meet.Start < DateTime.Now && meet.End < DateTime.Now)
            {
                state = 3;
            }
            //已预定
            else if (meet.Start > DateTime.Now && meet.End > DateTime.Now)
            {
                state = 1;
            }
            //进行中
            else if (meet.Start <= DateTime.Now && meet.End >= DateTime.Now)
            {
                state = 2;
            }
            meet.CreateID = dal.GetUserID(meet.Organizer);

            meet.state = state;
            if (meet.AttendeesList.Count > 0)
            {
                foreach (var Attendee in meet.AttendeesList)
                {
                    ParticipantIDs.Append(dal.GetUserID(Attendee.Address)).Append(",");
                }
                meet.ParticipantIDs = ParticipantIDs.ToString();
            }

            return meet;
        }
        public static ExchangeService getExChangeHelper()
        {
            service = new ExchangeService(EwsVersion);
            service.Credentials = new WebCredentials(EWSAccount, EWSAccountPwd);
            service.Url = new Uri(EWSUrl);
            return service;
        }
        public static ExchangeService getExChangeHelper(string EmailAdress)
        {
            service = new ExchangeService(EwsVersion);
            service.Credentials = new WebCredentials(EWSAccount, EWSAccountPwd);
            service.Url = new Uri(EWSUrl);
            service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, EmailAdress);
            return service;
        }
        public static ExchangeService getExChangeHelper(int version, string account, string ewsPwd, string ewsUrl)
        {
            service = new ExchangeService((ExchangeVersion)version);
            service.Credentials = new WebCredentials(account, UCommonWork.Common.Commons.MD5DecodeString(ewsPwd));
            service.Url = new Uri(ewsUrl);
            return service;
        }
        public static ExchangeService getExChangeHelper(string EmailAdress, ExchangeVersion version)
        {
            service = new ExchangeService(version);
            service.Credentials = new WebCredentials(EWSAccount, EWSAccountPwd);
            service.Url = new Uri(EWSUrl);
            service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, EmailAdress);
            return service;
        }
        /// <summary>
        /// 会议对象
        /// </summary>
        /// <param name="ap"></param>
        /// <param name="SendByEimai">发送人，协调人</param>
        /// <returns></returns>
        public string SendMeeting(EmailEntity ap, string SendByEimai, out string itemId)
        {
            try
            {


                service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, SendByEimai);
                //初始化会议对象
                Appointment appointment = new Appointment(service);
                //会议主题
                appointment.Subject = ap.Subject;
                //会议内容
                appointment.Body = ap.Body;
                //会议开始
                appointment.Start = ap.Start;
                //会议结束
                appointment.End = ap.End;
                //会议的位置
                appointment.Location = ap.Location;

                //添加与会者
                foreach (var email in ap.AttendeesList)
                {
                    appointment.RequiredAttendees.Add(new Attendee()
                    {
                        Address = email.Address,
                        Name = email.Name
                    });
                }
                //保存会议
                ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
                appointment.Save();
                Appointment item = Appointment.Bind(service, appointment.Id);
                itemId = item.Id.UniqueId;
                return item.ICalUid;


            }
            catch (Exception ex)
            {
                itemId = "";
                return ex.ToString();
            }
        }
        /// <summary>
        /// 更新会议信息
        /// </summary>
        /// <param name="ap"></param>
        /// <param name="SendByEimai"></param>
        public bool UpdateMeeting(EmailEntity ap, string SendByEimai, bool IsAuto, out string error)
        {
            var bResult = true;
            error = "";
            try
            {


                service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, SendByEimai);
                ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
                var appointment = GetEmailListByItemID(new ExchangeQuery(ap.ID, SendByEimai, ap.OldStart, ap.OldEnd, "")).Result;
                //初始化会议对象
                if (appointment.AppointmentType == AppointmentType.Occurrence || appointment.AppointmentType == AppointmentType.RecurringMaster || appointment.AppointmentType == AppointmentType.Exception)
                {
                    error = "更新周期会议请在outlook上操作！";
                    return false;
                }
                //会议主题
                appointment.Subject = ap.Subject;
                //会议内容
                appointment.Body = ap.Body;
                //会议开始
                appointment.Start = ap.Start;
                //会议结束
                appointment.End = ap.End;
                //会议的位置
                appointment.Location = ap.Location;
                if (!IsAuto)
                {
                    foreach (var email in ap.AttendeesList)
                    {
                        appointment.RequiredAttendees.Add(new Attendee()
                        {
                            Address = email.Address,
                            Name = email.Name
                        });
                    }
                }
                //添加与会者

                //修改会议
                appointment.Update(ConflictResolutionMode.AlwaysOverwrite, SendInvitationsOrCancellationsMode.SendToAllAndSaveCopy);
            }
            catch (Exception ex)
            {
                CLogger.Info(ex.Message);
                bResult = false;
                throw ex;
            }
            return bResult;
        }
        /// <summary>
        /// 取消会议
        /// </summary>
        /// <param name="ap"></param>
        /// <param name="address"></param>
        /// <returns></returns>
        public bool CannelMeeting(EmailEntity ap, string address, out string error)
        {
            error = "";
            try
            {


                service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, address);
                //初始化会议对象
                var emaill = ExChangeHelper.GetEmailListByItemID(new ExchangeQuery(ap.ID, address, ap.Start, ap.End, "")).Result;
                //初始化会议对象
                Appointment appointment = Appointment.Bind(service,
                emaill.Id);
                if (appointment.AppointmentType == AppointmentType.Occurrence || appointment.AppointmentType == AppointmentType.RecurringMaster || appointment.AppointmentType == AppointmentType.Exception)
                {
                    error = "周期会议取消请在outlook上操作！";
                    return false;
                }
                // Delete the meeting by using the Delete method.
                // 取消后，之前创建的会议标题前会加上已取消三个字
                appointment.Delete(DeleteMode.MoveToDeletedItems, SendCancellationsMode.SendToAllAndSaveCopy);
                return true;
            }
            catch (Exception ex)
            {
                CLogger.Info(ex.Message);
                return false;
                throw;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ap">会议信息，传入id</param>
        /// <param name="address">发送人邮箱，</param>
        /// <returns></returns>
        public static async Task<Appointment> GetEmailListByItemID(ExchangeQuery query)
        {

            try
            {

                service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, query.address);
                //初始化会议对象
                //Appointment oAppt = Appointment.Bind(serv, ItemId, new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End,AppointmentSchema.Body, AppointmentSchema.RequiredAttendees, AppointmentSchema.Organizer, AppointmentSchema.Location, AppointmentSchema.Id, AppointmentSchema.ICalUid));
                var view = new CalendarView(query.start, query.end);
                view.PropertySet = new PropertySet(AppointmentSchema.ICalUid);
                //var userMeet = UserService.FindAppointments(WellKnownFolderName.Calendar,view);
                CalendarFolder calendar = CalendarFolder.Bind(service, WellKnownFolderName.Calendar, new PropertySet());
                // Set the start and end time and number of appointments to retrieve.

                // Limit the properties returned to the appointment's subject, start time, and end time.

                FindItemsResults<Appointment> appointments = calendar.FindAppointments(view);
                var id = appointments.Where(i => i.ICalUid == query.Icaluid).FirstOrDefault();

                Appointment oApt = Appointment.Bind(service, id.Id, new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End, AppointmentSchema.Body, AppointmentSchema.RequiredAttendees, AppointmentSchema.Organizer, AppointmentSchema.Location, AppointmentSchema.Id, AppointmentSchema.ICalUid, AppointmentSchema.AppointmentType));
                return oApt;
            }
            catch (Exception ex)
            {
                CLogger.Info($"{ex.Message}::::未查询到用户：{query.address},开始时间：{query.start};结束时间：{query.end},id:{query.Icaluid}dateme:{DateTime.Now}");
                var fail = true;
                var count = 1;
                Appointment meet = null;
                while (fail)
                {
                    if (count > 4)
                    {
                        CLogger.Info($"{ex.Message}::::未查询到用户：{query.address},开始时间：{query.start};结束时间：{query.end},id:{query.Icaluid}dateme:{DateTime.Now}-已经20秒过去~");
                        break;
                    }
                    meet = await GetMeetByItemID(query);
                    if (meet != null)
                    {
                        fail = false;

                        CLogger.Info($"{ex.Message}::::未查询到用户：{query.address},开始时间：{query.start};结束时间：{query.end},id:{query.Icaluid} datetime:{DateTime.Now}");
                    }
                    else
                    {


                    }
                    count++;
                }
                return meet;
            }

        }
        public static Task<Appointment> GetMeetByItemID(ExchangeQuery query)
        {
            Thread.Sleep(5000);
            try
            {
                var serv = getExChangeHelper(query.address);
                //初始化会议对象
                //Appointment oAppt = Appointment.Bind(serv, ItemId, new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End,AppointmentSchema.Body, AppointmentSchema.RequiredAttendees, AppointmentSchema.Organizer, AppointmentSchema.Location, AppointmentSchema.Id, AppointmentSchema.ICalUid));
                var view = new CalendarView(query.start.AddDays(-1), query.end.AddDays(180));
                view.PropertySet = new PropertySet(AppointmentSchema.ICalUid);
                //var userMeet = UserService.FindAppointments(WellKnownFolderName.Calendar,view);
                CalendarFolder calendar = CalendarFolder.Bind(serv, WellKnownFolderName.Calendar, new PropertySet());
                // Set the start and end time and number of appointments to retrieve.

                // Limit the properties returned to the appointment's subject, start time, and end time.

                FindItemsResults<Appointment> appointments = calendar.FindAppointments(view);
                var id = appointments.Where(i => i.ICalUid == query.Icaluid).FirstOrDefault();

                Appointment oApt = Appointment.Bind(serv, id.Id, new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End, AppointmentSchema.Body, AppointmentSchema.RequiredAttendees, AppointmentSchema.Organizer, AppointmentSchema.Location, AppointmentSchema.Id, AppointmentSchema.ICalUid, AppointmentSchema.AppointmentType));
                return System.Threading.Tasks.Task.FromResult(oApt);
            }
            catch (Exception ex)
            {
                CLogger.Info($"每五秒查询：：{ex.Message}::::未查询到用户：{query.address},开始时间：{query.start};结束时间：{query.end},id:{query.Icaluid}");
                Appointment error = null;
                return System.Threading.Tasks.Task.FromResult(error);
                throw;
            }

        }
        public static EmailEntity GetEmailEntity(Appointment appointment)
        {
            return getEmailEntity(appointment);
        }
        public static Appointment GetEmailListByMasterID(ExchangeQuery query)
        {

            try
            {
                var serv = getExChangeHelper(query.address);
                //初始化会议对象
                //Appointment oAppt = Appointment.Bind(serv, ItemId, new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End,AppointmentSchema.Body, AppointmentSchema.RequiredAttendees, AppointmentSchema.Organizer, AppointmentSchema.Location, AppointmentSchema.Id, AppointmentSchema.ICalUid));
                var view = new CalendarView(query.start.AddDays(-1), query.end.AddDays(1));
                view.PropertySet = new PropertySet(AppointmentSchema.ICalUid);
                //var userMeet = UserService.FindAppointments(WellKnownFolderName.Calendar,view);
                CalendarFolder calendar = CalendarFolder.Bind(serv, WellKnownFolderName.Calendar, new PropertySet(AppointmentSchema.ICalUid));
                // Set the start and end time and number of appointments to retrieve.

                // Limit the properties returned to the appointment's subject, start time, and end time.

                FindItemsResults<Appointment> appointments = calendar.FindAppointments(view);
                var id = appointments.Where(i => i.ICalUid == query.Icaluid).FirstOrDefault();
                var ccc = appointments.Where(i => i.ICalUid == query.Icaluid);
                Appointment oApt = Appointment.Bind(serv, id.Id, new PropertySet());
                return oApt;
            }
            catch (Exception ex)
            {
                CLogger.Info($"{ex.Message}::::未查询到用户：{query.address},开始时间：{query.start};结束时间：{query.end},id:{query.Icaluid}");
                return null;
                throw;
            }

        }
        /// <summary>
        /// 会议室日历
        /// </summary>
        /// <param name="service"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public static FindItemsResults<Appointment> GetMeeting(ExchangeService service, DateTime startDate, DateTime endDate)
        {


            CalendarFolder calendar = CalendarFolder.Bind(service, WellKnownFolderName.Calendar, new PropertySet());
            // Set the start and end time and number of appointments to retrieve.
            CalendarView cView = new CalendarView(startDate, endDate, 1000);
            // Limit the properties returned to the appointment's subject, start time, and end time.
            //   cView.PropertySet = new PropertySet(AppointmentSchema.Start,AppointmentSchema.End,AppointmentSchema.ICalUid,AppointmentSchema.IsRecurring,AppointmentSchema.AppointmentType);
            cView.PropertySet = new PropertySet(BasePropertySet.FirstClassProperties);
            FindItemsResults<Appointment> appointments = calendar.FindAppointments(cView);
            return appointments;

        }
        public static FindItemsResults<Appointment> GetMeetingForUser(ExchangeService service, DateTime startDate, DateTime endDate)
        {

            var aaa = service.FindAppointments(WellKnownFolderName.Calendar, new CalendarView(startDate, endDate));
            //// Initialize the calendar folder object with only the folder ID. 
            //CalendarFolder calendar = CalendarFolder.Bind(service, WellKnownFolderName.Calendar, new PropertySet());
            //// Set the start and end time and number of appointments to retrieve.
            //CalendarView cView = new CalendarView(startDate, endDate, 1000);
            //// Limit the properties returned to the appointment's subject, start time, and end time.
            //cView.PropertySet = new PropertySet(new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End, AppointmentSchema.Body, AppointmentSchema.RequiredAttendees, AppointmentSchema.Organizer, AppointmentSchema.Location, AppointmentSchema.Id, AppointmentSchema.ICalUid));
            //// Retrieve a collection of appointments by using the calendar view.
            //FindItemsResults<Appointment> appointments = calendar.FindAppointments(cView);

            return aaa;

        }
        public static void GetRecurringMeeting(ExchangeService service)
        {
            List<Appointment> foundAppointments = new List<Appointment>();
            // Create a calendar view to search the calendar folder and specify the properties to return.
            CalendarView calView = new CalendarView(DateTime.Now, DateTime.Now.AddDays(180));
            calView.PropertySet = new PropertySet(BasePropertySet.IdOnly,
                                                    AppointmentSchema.Subject,
                                                    AppointmentSchema.Start,
                                                    AppointmentSchema.End,
                                                    AppointmentSchema.IsRecurring,
                                                    AppointmentSchema.AppointmentType);
            // Retrieve a collection of calendar items.
            FindItemsResults<Appointment> findResults = service.FindAppointments(WellKnownFolderName.Calendar, calView);
            // Add all calendar items in your view that are occurrences or exceptions to your collection.
            foreach (Appointment appt in findResults.Items)
            {
                Appointment calendarItem = Appointment.Bind(service, appt.Id, new PropertySet(AppointmentSchema.AppointmentType));
                Appointment recurrMaster = new Appointment(service);
                PropertySet props = new PropertySet(AppointmentSchema.AppointmentType,
                                                    AppointmentSchema.Subject,
                                                    AppointmentSchema.FirstOccurrence,
                                                    AppointmentSchema.LastOccurrence,
                                                    AppointmentSchema.ModifiedOccurrences,
                                                    AppointmentSchema.DeletedOccurrences);
                // If the item ID is not for a recurring master, retrieve the recurring master for the series.
                switch (calendarItem.AppointmentType)
                {
                    // Calendar item is a recurring master so use Appointment.Bind
                    case AppointmentType.RecurringMaster:
                        recurrMaster = Appointment.Bind(service, appt.Id, props);
                        break;
                    // The calendar item is a single instance meeting, so there are no instances to modify or delete.
                    case AppointmentType.Single:
                        Console.WriteLine("Item id must reference a calendar item that is part of a recurring series.");
                        return;
                    // The calendar item is an occurrence in the series, so use BindToRecurringMaster.
                    case AppointmentType.Occurrence:
                        recurrMaster = Appointment.BindToRecurringMaster(service, appt.Id, props);
                        break;
                    // The calendar item is an exception to the series, so use BindToRecurringMaster.                
                    case AppointmentType.Exception:
                        recurrMaster = Appointment.BindToRecurringMaster(service, appt.Id, props);
                        break;
                }
                // View the first occurrence, last occurrence, and number of modified and deleted occurrences associated with the recurring master.
                Console.WriteLine("Information for the {0} recurring series:", recurrMaster.Subject);
                Console.WriteLine("The start time for the first appointment with id \t{0} was on \t{1}.",
                                    recurrMaster.FirstOccurrence.ItemId.ToString().Substring(144),
                                    recurrMaster.FirstOccurrence.Start.ToString());
                Console.WriteLine("The start time for the last appointment with id \t{0} will be on \t{1}.",
                                    recurrMaster.LastOccurrence.ItemId.ToString().Substring(144),
                                    recurrMaster.LastOccurrence.Start.ToString());
                Console.WriteLine("There are {0} modified occurrences and {1} deleted occurrences.",
                                    recurrMaster.ModifiedOccurrences == null ? "no" : recurrMaster.ModifiedOccurrences.Count.ToString(),
                                    recurrMaster.DeletedOccurrences == null ? "no" : recurrMaster.DeletedOccurrences.Count.ToString());
                // Bind to the first occurrence of a series by using its index.
                Appointment firstOccurrence = Appointment.BindToOccurrence(service,
                                                                            recurrMaster.Id,
                                                                            1, // Index of first item is 1, not 0.
                                                                            new PropertySet(AppointmentSchema.AppointmentType,
                                                                                            AppointmentSchema.Start));
                Console.WriteLine("Compare the start times for a recurring master's first occurrence " +
                                    "and the occurrence found at index 1 using the BindToOccurrence method:");
                Console.WriteLine("The appointment at index 1 has a start time of\t\t\t\t {0}\n" +
                                    "Which matches that of the first occurrence on the recurring master: \t {1}",
                                    firstOccurrence.Start.ToString(),
                                    recurrMaster.FirstOccurrence.Start.ToString());
            }
        }
    }
}
